package com.zmn.plat.anole.config.interceptor;

import com.zmn.plat.common.util.encrypt.EncryptDecryptUtils;
import com.zmn.plat.common.util.encrypt.annotation.EncryptDecryptClass;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 描述: 加密字段null值处理
 *
 * @author jiafei
 * @version 1.0
 * @since 2021/9/14 11:42
 */
//@Component
@Slf4j
@Intercepts(@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}))
public class UpdateInterceptor implements Interceptor {

	@Override
	public Object intercept(Invocation invocation) throws Throwable {

		fillField(invocation);
		return invocation.proceed();
	}

	private void fillField(Invocation invocation) throws IllegalAccessException {

		Object[] args = invocation.getArgs();
		SqlCommandType sqlCommandType = null;
		for (int i = 0; i < args.length; i++) {
			Object arg = args[i];
			String className = arg.getClass().getName();
			log.info(i + " 参数类型：" + className);
			//第一个参数处理。根据它判断是否给“操作属性”赋值。
			//如果是第一个参数 MappedStatement
			if (arg instanceof MappedStatement) {
				MappedStatement ms = (MappedStatement) arg;
				sqlCommandType = ms.getSqlCommandType();
				log.info("操作类型：" + sqlCommandType);
				if (sqlCommandType == SqlCommandType.INSERT ||
					sqlCommandType == SqlCommandType.UPDATE) {//如果是“增加”或“更新”操作，则继续进行默认操作信息赋值。否则，则退出
					continue;
				} else {
					break;
				}
			}
			EncryptDecryptClass encryptDecryptClass = AnnotationUtils.findAnnotation(arg.getClass(),
																					 EncryptDecryptClass.class);
			if (Objects.isNull(encryptDecryptClass)) {
				continue;
			}
			Map<String, String> encryptFields = EncryptDecryptUtils.encryptFields(arg);
			Map<String, Field> fieldMap = Arrays.stream(FieldUtils.getAllFields(arg.getClass()))
												.collect(Collectors.toMap(Field::getName, Function
														.identity(), (v1, v2) -> v1));

			encryptFields.forEach((key, value) -> {
				if (Objects.isNull(value) || "".equals(value)) {
					Field field = fieldMap.get(key);
					field.setAccessible(true);
					try {
						field.set(arg, value);
					} catch (IllegalAccessException e) {
						log.error("加密失败,处理null报错");
						e.printStackTrace();
					}
				}
			});
		}
	}


	@Override
	public Object plugin(Object o) {

		return Plugin.wrap(o, this);
	}

	@Override
	public void setProperties(Properties properties) {

	}

}
